﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using AopAlliance.Intercept;
using System.Transactions;
using Flower.Workflow;

namespace Flower.Processing.Advices
{
    internal class Transaction : IMethodInterceptor
    {
        private readonly TimeSpan _timeout;

        public Transaction(TimeSpan timeout)
        {
            _timeout = timeout;
        }

        public object Invoke(IMethodInvocation invocation)
        {
            var processor = invocation.Arguments[0] as Processor;
            if (processor == null)
            {
                return invocation.Proceed();
            }

            var executionFlagsHolder = invocation.Target as IExecutionFlagsHolder;

            if
            (
                executionFlagsHolder != null &&
                executionFlagsHolder.ExecutionFlags.HasFlag(ExecutionFlags.NoTransaction)
            )
            {
                return invocation.Proceed();
            }

            var transOpts =
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = _timeout
                };
            using (var trn = new TransactionScope(TransactionScopeOption.Required, transOpts))
            {
                string trnId = System.Transactions.Transaction.Current.TransactionInformation.LocalIdentifier;

                processor.Log.Trace(() => string.Format("Transaction {0} started.", trnId));

                object retval = invocation.Proceed();
                trn.Complete();

                processor.Log.Trace(() => string.Format("Transaction {0} completed.", trnId));

                return retval;
            }
        }
    }
}
